package com.zzl.bonds.ticket.controller;

import com.zzl.apidoc.annotation.ApidocController;
import com.zzl.apidoc.annotation.ApidocOperation;
import com.zzl.apidoc.annotation.ApidocParam;
import com.zzl.bonds.ticket.constant.status.TicketCashingEnum;
import com.zzl.bonds.ticket.dto.CashTicketPage;
import com.zzl.bonds.ticket.dto.CashTicketUpdateDto;
import com.zzl.bonds.ticket.dto.SurveyInfo;
import com.zzl.bonds.ticket.dto.myticket.*;
import com.zzl.bonds.ticket.entity.TicketEntity;
import com.zzl.bonds.ticket.service.TicketService;
import com.zzl.general.common.apidoc.annotation.ApidocParamsPage;
import com.zzl.general.common.apidoc.annotation.ApidocResultKeyValR;
import com.zzl.general.common.apidoc.annotation.ApidocReturnPage;
import com.zzl.general.common.apidoc.annotation.ApidocReturnR;
import com.zzl.general.common.apidoc.constants.ResultTypeInR;
import com.zzl.general.common.ctrl.WebBaseCtrl;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.utils.LogUtils;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

/**
 * 我的票据
 *
 * @author sunpp
 * @date 2022-02-16 11:14:07
 */
@ApidocController("我的票据")
@RestController
@SuppressWarnings("javadoc")
@RequestMapping("bondsticket/ticket")
@Slf4j
public class TicketController extends WebBaseCtrl {
    @SuppressWarnings("all")
    @Autowired
    private TicketService ticketService;


    /**
     * 我持有的凭证
     */
    @GetMapping("/list")
    @ApidocOperation(description = "我持有的凭证", operationId = "/bondsticket/ticket/list12")
    @ApidocReturnPage(genericTypeClass = MyTicketPage.class)
    public Result list(@ApidocParamsPage(name = "params", keyName = {
            "ticketNo"
            , "ticketOpenStartTime"
            , "ticketOpenEndTime"
            , "transferStartTime"
            , "transferEndTime"
            , "receiptStartTime"
            , "receiptEndTime"
            , "startAmount"
            , "endAmount"
            , "openEnterpriseId"
            , "transferEnterpriseName"
            , "ticketTypeSource"
            , "page"
            , "order"
    }
            , keyDescription = {
            "凭证编号"
            , "开单开始日期"
            , "开单结束日期"
            , "转单开始日期"
            , "转单结束日期"
            , "签收开始日期"
            , "签收结束日期"
            , "开始金额"
            , "结束金额"
            , "开单单位"
            , "转单单位"
            , "票据数据来源,1:开单签收，2：转单签收，3融单留存4.转单留存，5转单失败，6融单失败"
            , "排序类型：create_time（默认）、invoice_time：开单日期、cash_time：到期日期，ticket_amount：凭证金额"
            , "排序方式：desc 降序（默认）asc 升序"})
                       @RequestParam Map<String, Object> params) {
        try {
            PageUtils page = ticketService.queryPage(params, this.getUser());
            return Result.ok().put("page", page);
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }


    /**
     * 转让中的凭证
     */
    @GetMapping("/getTransferIngList")
    @ApidocOperation(description = "转让中", operationId = "/bondsticket/ticket/getTransferIngList")
    @ApidocReturnPage(genericTypeClass = MyTicketPage.class)
    public Result getTransferIngList(@ApidocParamsPage(name = "params", keyName = {
            "ticketNo"
            , "financeInstitutyId"
            , "receiveEnterpriseName"
            , "startAmount"
            , "endAmount"
            , "page"
            , "order"
    }
            , keyDescription = {
            "凭证编号"
            , "金融机构"
            , "收单企业名称"
            , "开始金额"
            , "结束金额"
            , "排序类型：t.create_time（默认）、invoice_time：开单日期、cash_time：到期日期，ticket_all_amount：凭证金额"
            , "排序方式：desc 降序（默认）asc 升序"})
                                     @RequestParam Map<String, Object> params) {
        try {
            PageUtils page = ticketService.queryTransferIngPage(params, this.getUser());
            return Result.ok().put("page", page);
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }


    /**
     * 融资中的凭证
     */
    @GetMapping("/getFinanceIngList")
    @ApidocOperation(description = "融资中", operationId = "/bondsticket/ticket/getFinanceIngList")
    @ApidocReturnPage(genericTypeClass = MyTicketFinancePage.class)
    public Result getFinanceIngList(@ApidocParamsPage(name = "params", keyName = {
            "ticketNo"
            , "financeInstitutyId"
            , "startAmount"
            , "endAmount"
            , "page"
            , "order"
    }
            , keyDescription = {
            "凭证编号"
            , "金融机构"
            , "开始金额"
            , "结束金额"
            , "排序类型：create_time（默认）、sell_amount：融资本金、estimated_financing_interest：融资利息" +
            "，service_chage：服务费,instincty_name 金融机构名称,create_time 申请日期,cashTime 到期日期"
            , "排序方式：desc 降序（默认）asc 升序"})
                                    @RequestParam Map<String, Object> params) {
        try {
            PageUtils page = ticketService.queryFinanceIngPage(params, this.getUser());
            return Result.ok().put("page", page);
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }


    /**
     * 失效 的凭证
     */
    @GetMapping("/getInvalidIngList")
    @ApidocOperation(description = "失效", operationId = "/bondsticket/ticket/invallidIng")
    @ApidocReturnPage(genericTypeClass = MyTicketInvalidPage.class)
    public Result getInvalidingList(@ApidocParamsPage(name = "params", keyName = {
            "ticketNo"
            , "financeInstitutyId"
            , "ticketOpenStartTime"
            , "ticketOpenEndTime"
            , "startAmount"
            , "endAmount"
            , "openEnterpriseId"
            , "transferEnterpriseName"
            , "invalidReason"
            , "transferStartTime"
            , "transferEndTime"
            , "receiptStartTime"
            , "receiptEndTime"
            , "page"
            , "order"
    }
            , keyDescription = {
            "凭证编号"

            , "金融机构"
            , "开单开始日期"
            , "开单结束日期"
            , "开始金额"
            , "结束金额"
            , "开单企业"
            , "转单企业"
            , "失效原因,1母单被拆分，2 转单失败，3融单失败，4转单留存回滚，5融单留存回滚"
            , "转单开始日期"
            , "转单结束日期"
            , "签收开始日期"
            , "签收结束日期"
            , "排序类型：create_time（默认）、invoice_time：开单日期、cash_time：到期日期，ticket_amount：凭证金额"
            , "排序方式：desc 降序（默认）asc 升序"})
                                    @RequestParam Map<String, Object> params) {
        try {
            PageUtils page = ticketService.queryInvalidIngPage(params, this.getUser());
            return Result.ok().put("page", page);
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 凭证信息
     */
    @GetMapping("/info/{id}")
    @ApidocOperation(description = "凭证信息", operationId = "8002")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = MyTicketDetail.class)
    })
    public Result info(@ApidocParam(name = "我的票据id", required = true) @PathVariable("id") String id) {
        try {

            return Result.ok().put("data", ticketService.getMyTicketDetail(id));
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 业务信息
     */
    @GetMapping("/getTicketBusinessDetail/{id}")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "data", valueClass = MyTicketBusinessDetail.class)
    })
    public Result getTicketBusinessDetail(@ApidocParam(name = "我的票据id", required = true) @PathVariable("id") String id) {
        try {

            return Result.ok().put("data", ticketService.getTicketBusinessDetail(id));
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 信息
     */
    @GetMapping("/getById/{id}")
    @ApidocOperation(description = "我的票据数据详情", operationId = "8012")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_OBJECT, key = "ticket", valueClass = TicketEntity.class)
    })
    public Result getById(@ApidocParam(name = "我的票据id", required = true) @PathVariable("id") String id) {
        TicketEntity ticket = ticketService.getById(id);
        return Result.ok().put("ticket", ticket);
    }


    /**
     * 兑付列表
     */
    @GetMapping("/cashingPage")
    @ApidocOperation(description = "兑付列表", operationId = "/bondsticket/ticket/list231")
    @ApidocReturnPage(genericTypeClass = CashTicketPage.class)
    public Result cashingPage(@ApidocParamsPage(name = "params", keyName = {
            "ticketNo"
            , "openEnterpriseId"
            , "enterpriseName"
            , "advancePaymentStatus"
            , ""
            , "page"
            , "order"
    }
            , keyDescription = {
            "凭证编号"
            , "出单单位"
            , "收单单位"
            , "1，到期未兑付，2未到期待兑付，3已兑付,6审批中"
            , "排序类型：create_time（默认）、invoice_time：开单日期、cash_time：到期日期，ticket_amount：凭证金额"
            , "排序方式：desc 降序（默认）asc 升序"})
                              @RequestParam Map<String, Object> params) {
        try {
            String advancePaymentStatus = (String) params.get("advancePaymentStatus");
            if ("1".equals(advancePaymentStatus)) {
                params.put("cashStatus", Arrays.asList(TicketCashingEnum.OVERDUE_NON_PAYMENT.getCode()));
            } else if ("2".equals(advancePaymentStatus)) {
                params.put("cashStatus", Arrays.asList(TicketCashingEnum.OUTSTANDING.getCode(), TicketCashingEnum.WAITING_FOR_PAYMENT.getCode()
                        , TicketCashingEnum.APPROVE_CASHED.getCode()));
            } else if ("3".equals(advancePaymentStatus)) {
                params.put("cashStatus", Arrays.asList(TicketCashingEnum.OVERDUE_CASHED.getCode(), TicketCashingEnum.CASHED.getCode()));
            } else if ("6".equals(advancePaymentStatus)) {
                params.put("cashStatus", Arrays.asList(TicketCashingEnum.APPROVE_CASHED.getCode()));
            }
            PageUtils page = ticketService.cashingPage(params, this.getUser(), advancePaymentStatus);
            return Result.ok().put("page", page);
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 获取兑付列表兑付列表
     */
    @GetMapping("/getCashList/{ticketOpenId}")
    @ApidocOperation(description = "获取兑付列表兑付列表", operationId = "/bondsticket/ticket/list123")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_COLLOCTION, key = "list", valueClass = CashTicketPage.class)
    })
    public Result getCashList(@ApidocParam(name = "票据id", required = true) @PathVariable("ticketOpenId") String ticketId) {
        try {
            return Result.ok().put("list", ticketService.getCashList(ticketId, this.getUser()));
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 获取平台端兑付列表兑付列表
     */
    @GetMapping("/getPlatformCashList/{ticketOpenId}")
    @ApidocOperation(description = "获取兑付列表兑付列表", operationId = "/bondsticket/ticket/list1")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_COLLOCTION, key = "list", valueClass = CashTicketPage.class)
    })
    public Result getPlatformCashList(@ApidocParam(name = "票据id", required = true) @PathVariable("ticketOpenId") String ticketOpenId) {
        try {
            return Result.ok().put("list", ticketService.getPlatformCashList(ticketOpenId, this.getUser()));
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 兑付
     */
    @GetMapping("/cashTicket/{ticketOpenId}")
    @ApidocOperation(description = "兑付", operationId = "/bondsticket/ticket/cashTicket/11")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_COLLOCTION, key = "list", valueClass = TicketEntity.class)
    })
    public Result cashTicket(@ApidocParam(name = "票据id", required = true) @PathVariable("ticketOpenId") String ticketOpenId) {
        try {
            ticketService.cashTicket(ticketOpenId, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }


    /**
     * 平台兑付
     */
    @PutMapping("/ApprovalCashing")
    @ApidocOperation(description = "平台兑付", operationId = "9004/12")
    @ApidocReturnR
    public Result recheckTransferOrder(@ApidocParam(name = "修改的转让申请单对象值", required = true) @Validated @RequestBody CashTicketUpdateDto cashTicketUpdateDto) {
        try {
            ticketService.approvalCashing(cashTicketUpdateDto, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
    }

    /**
     * 平台兑付驳回
     */
    @PutMapping("/approvalCashingReject")
    @ApidocOperation(description = "平台兑付驳回", operationId = "9004/13")
    @ApidocReturnR
    public Result approvalCashingReject(@ApidocParam(name = "修改的转让申请单对象值", required = true) @Validated @RequestBody CashTicketUpdateDto cashTicketUpdateDto) {
        try {
            ticketService.approvalCashingReject(cashTicketUpdateDto, this.getUser());
            return Result.ok();
        } catch (SysException e) {
            LogUtils.logSysException(log, e);
            return Result.error(e.getMsg());
        }
    }


    /**
     * 供应商-概况
     */
    @GetMapping("/survey")
    @ApidocOperation(description = "供应商-概况", operationId = "/bondsticket/ticket/cashTicket")
    @ApidocReturnR(otherkv = {
            @ApidocResultKeyValR(resultType = ResultTypeInR.TYPE_COLLOCTION, key = "list", valueClass = SurveyInfo.class)
    })
    public Result cashTicket() {
        try {
            SurveyInfo surveyInfo=ticketService.survey( this.getUser());
            return Result.ok();
        } catch (SysException e) {
            return Result.error(e.getMsg());
        }
    }
}
